package spark.core.java;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.api.java.function.VoidFunction;
import scala.Tuple2;

import java.util.Arrays;

/**
 * 排序的wordcount程序
 */
public class SortWordCount {
    public static void main(String[] args) {
        //编写spark应用程序
        SparkConf conf = new SparkConf().setAppName("SortWordCount").setMaster("local");
        JavaSparkContext sc = new JavaSparkContext(conf);
        JavaRDD<String> lines = sc.textFile("datas/hello.txt");
        //对LINES RDD 执行maptopair 算子，将每一行映射为（line,1）的这种key-value的格式
        //然后后面才能统计每一行出现的次数

        JavaRDD<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
            public Iterable<String> call(String s) throws Exception {
                return Arrays.asList(s.split(" "));
            }
        });

        JavaPairRDD<String, Integer> pairs = words.mapToPair(new PairFunction<String, String, Integer>() {
            public Tuple2<String, Integer> call(String s) throws Exception {
                return new Tuple2<String, Integer>(s, 1);
            }
        });
        //对pairs RDD执行reduceBykey算子，统计出每一行出现的总次数
        JavaPairRDD<String, Integer> lineCounts = pairs.reduceByKey(new Function2<Integer, Integer, Integer>() {
            public Integer call(Integer v1, Integer v2) throws Exception {
                return v1 + v2;
            }
        });

        //到这里为止，就得到了每个单词出现的次数
        //但是问题是，我们的新需求，是要按照每个单词次数的顺序，降序排序
        //我们需要将RDD转换成（3，hello）（2，you）的这种格式。才能根据单词出现次数进行排序吧！
        //进行key-value的反转
        JavaPairRDD<Integer, String> countWords = lineCounts.mapToPair(new PairFunction<Tuple2<String, Integer>, Integer, String>() {
            public Tuple2<Integer, String> call(Tuple2<String, Integer> t) throws Exception {
                return new Tuple2<Integer, String>(t._2(),t._1());
            }
        });
        //按照key进行排序
        JavaPairRDD<Integer, String> sortedCountWords =  countWords.sortByKey(false);
        //再次进行反转
        JavaPairRDD<String, Integer> sortedWordCounts = sortedCountWords.mapToPair(new PairFunction<Tuple2<Integer, String>, String, Integer>() {
            public Tuple2<String, Integer> call(Tuple2<Integer, String> t) throws Exception {
                return new Tuple2<String, Integer>(t._2(),t._1());
            }
        });

        //执行一个action操作，
        sortedWordCounts.foreach(new VoidFunction<Tuple2<String, Integer>>() {
            public void call(Tuple2<String, Integer> t) throws Exception {
                System.out.println(t._1() + " appears " + t._2() + " times.");
            }
        });

        sc.close();
    }
}
